<!--
 * @Author: zhangxiangsheng 1026583651@qq.com
 * @Date: 2024-06-17 15:04:34
 * @LastEditors: zhangxiangsheng 1026583651@qq.com
 * @LastEditTime: 2024-06-20 14:21:21
 * @FilePath: \appGly\components\formz\components\dz.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
-->
<template>
  <view class="">
    <u-form-item
      :label="item.label"
      :prop="item.value"
      borderBottom
      ref="item1"
    >
      <u-button
        :text="value || $z.$t('请选择')"
        :hairline="false"
        :customStyle="btnstyle"
        @click="btntap"
      ></u-button>
    </u-form-item>

    <u-popup :show="show" mode="right">
      <view class="popupcontent">
        <u-navbar title="地址选择" :autoBack="false" @leftClick="popupback" />
        <view style="width: 100vw"></view>
        <view class="map" id="amap" ref="amap"></view>
        <view class="mapview">
          <view class="t">
            <view class="Address1">
              <view>{{ Address1 }}</view>
              <view class="iconfont iconquyu" @click="dwfn"></view>
            </view>
            <view class="Address2">
              <u--input
                placeholder="请输入内容"
                border="none"
                v-model="Address2"
              ></u--input>
            </view>
          </view>
          <view class="b">
            <u-button type="primary" @click="save">
              {{ $z.$t("确认位置") }}
            </u-button>
          </view>
        </view>
      </view>
    </u-popup>
    <view
      :mapOverlays="mapOverlays"
      :change:mapOverlays="aMapRenderJs.mapOverlaysinit"
    ></view>
  </view>
</template>

<script>
  import cityjs from "./cityjs";
  export default {
    props: {
      item: {
        typeof: Object,
        default: () => {
          return {};
        },
      },
      data: {
        typeof: Object,
        default: () => {
          return {};
        },
      },
      value: {
        typeof: [String, Number, Boolean, Array, Object],
        default: () => {
          return "";
        },
      },
    },
    data() {
      return {
        show: false,
        showtext: "",
        btnstyle: {
          border: "none",
          padding: "0",
          justifyContent: "flex-start",
        },
        wz: {
          lng: "116.39742",
          lat: "39.909",
        },
        Address1: "",
        Address2: "",
        mpt: "",
        AreaCode: "",
        latitude: "39.909",
        longitude: "116.39742",
      };
    },
    watch: {
      value: {
        async handler() {
          // if (this.value == "") {
          //   let GetMappt = await this.$z.request("/GetMappt");
          //   this.$emit("input", GetMappt[0].mpt);
          // }
        },
        immediate: true,
      },
    },
    computed: {
      mapOverlays() {
        return {
          show: this.show,
          latitude: this.latitude,
          longitude: this.longitude,
        };
      },
    },
    methods: {
      async dwfn() {
        if (Object.keys(this.$store.state.config.wz).length == 0) {
          await this.$store.dispatch("config/getLocation");
        }
        let wz = {
          ...this.$store.state.config.wz,
        };
        let wz2 = uni.$z.gps.bd09togcj02(wz.lng, wz.lat);
        this.wz = {
          lng: wz2[0],
          lat: wz2[1],
        };
        this.latitude = this.wz.lat + 0.00001;
        this.longitude = this.wz.lng + 0.00001;
        setTimeout(() => {
          this.latitude = this.wz.lat;
          this.longitude = this.wz.lng;
        });
      },
      popupback() {
        this.show = false;
      },
      async btntap(item) {
        let modelValuesmpt = this.item.modelValues.find((e) => e.type == "mpt");
        if (this.data[modelValuesmpt.value]) {
          let mpt = [];
          mpt = this.data[modelValuesmpt.value];
          mpt = mpt.replace("POINT(", "");
          mpt = mpt.replace(")", "");
          mpt = mpt.split(" ");
          // POINT(120.291906 32.7589
          let wz2 = uni.$z.gps.bd09togcj02(mpt[0], mpt[1]);
          this.latitude = wz2[1];
          this.longitude = wz2[0];
        } else {
          await this.dwfn();
        }
        // latitude: this.latitude,
        // longitude: this.longitude,
        this.show = true;
      },
      mapchange(data) {
        data.regeocode.addressComponent.city =
          typeof data.regeocode.addressComponent.city == "string"
            ? data.regeocode.addressComponent.city
            : "";
        this.Address1 = `${data.regeocode.addressComponent.province} ${data.regeocode.addressComponent.city}`;
        this.Address2 = `${data.regeocode.formatted_address.replaceAll(
          `${data.regeocode.addressComponent.province}${data.regeocode.addressComponent.city}`,
          ""
        )}`;
        this.mpt = data.mpt;
        let cityjsxs = cityjs.flat();
        let r = cityjsxs.find((e) => {
          return (
            e.label == data.regeocode.addressComponent.city ||
            e.label == data.regeocode.addressComponent.province
          );
        });
        if (r) {
          this.AreaCode = r.value;
        }
      },
      save() {
        let modelValues = this.item.modelValues;
        let reqdata = {};
        modelValues.forEach((e) => {
          if (e.type == "AreaCode") {
            reqdata[e.value] = this.AreaCode;
          } else if (e.type == "Address") {
            reqdata[e.value] = `${this.Address1}${this.Address2}`;
          } else if (e.type == "mpt") {
            reqdata[e.value] = this.mpt;
          }
        });
        this.$emit("update:data", {
          ...this.data,
          ...reqdata,
        });
        this.$forceUpdate();
        this.show = false;
      },
    },
  };
</script>
<script module="aMapRenderJs" lang="renderjs">
   import chwz from "@/static/map/chwz.png";
   import cityjs from "./cityjs.js";
  export default {
  	data() {
  		return {
  			amapOverlays: {},
  			map: "",
        marker:"",
  			zoom: 15,
  			// dwimg,
  			showitem: {},
        regeocode:{}
  		}
  	},
  	mounted() {
  		// this.aMapinit()
  	},
  	computed: {
  		watchmap() {
  			return [this.map, this.amapOverlays]
  		}
  	},
  	watch: {
  		watchmap() {
  			if (!this.amapOverlays || !this.amapOverlays.show) {
          this.map=""
  				return;
  			}
  			if (this.map == "") {
  				setTimeout(() => {
  					this.aMapinit()
  				}, 300);
  			}else{
          this.amapOverlayschange()
        }
  		}
  	},
  	methods: {
  		aMapinit() {
  			if (typeof window.AMap === 'function') {
  				this.initAmap();
  			} else {

  				// window._AMapSecurityConfig = {
  				// 	securityJsCode: A_MAP_SECRET_KEY,
  				// };
  				const script = document.createElement('script');
  				script.src =
  					`https://maps.googleapis.com/maps/api/js?key=AIzaSyB6uNFNJWPMLLwO6_MF2FP4E4xO4ez0gPY&libraries=maps,marker&v=beta&libraries=marker`
  				script.onload = this.initAmap.bind(this);
  				document.head.appendChild(script);
  			}
  		},
  		async initAmap() {
  			const {
  				Map
  			} = await google.maps.importLibrary("maps");

        let latlng=new google.maps.LatLng(this.amapOverlays.latitude, this.amapOverlays.longitude)

  			this.map = new Map(document.getElementById("amap"), {
  				center: latlng,
  				zoom: 14,
  				mapId: "4504f8b37365c3d0",
  				clickableIcons: false,
  				showMapPoi: false,
  				disableDefaultUI: true,
  			});
        this.mapcenter_changed()
  			this.marker = new google.maps.Marker({
  				position: latlng,
  				icon: chwz,
  				map: this.map,
  			});
        this.map.addListener("center_changed", (e) => {

          uni.$u.debounce(async ()=>{
           this.mapcenter_changed()
          })
        });
  		},

      async mapcenter_changed(){
          let point=this.map.getCenter()
          this.marker.setPosition(point)
          let data = await uni.$z.request({
            url: `https://restapi.amap.com/v3/geocode/regeo?key=517d8820e2d55ee1b86b5b0f080fc405&output=JSON&location=${point.lng()},${point.lat()}`,
            method: "post",
          })
          if(data.status=="1"){
            // this.regeocode=data.regeocode;
            this.$ownerInstance.callMethod('mapchange', {
              regeocode: data.regeocode,
              mpt:`POINT(${point.lng()} ${point.lat()})`
            })
          }
      },
  		mapOverlaysinit(mapOverlays) {
  			this.amapOverlays = mapOverlays;

  		},
      amapOverlayschange(){
        let latlng=new google.maps.LatLng(this.amapOverlays.latitude, this.amapOverlays.longitude)
        this.map.setCenter(latlng)
      }


  	}
  }
</script>
<style lang="scss">
  .popupcontent {
    height: 100vh;
    display: flex;
    flex-direction: column;

    #amap {
      flex: 1;
      height: 0;
    }
  }

  .mapview {
    position: absolute;
    left: 30rpx;
    right: 30rpx;
    bottom: 30rpx;

    .t {
      margin-bottom: 40rpx;
      background: #fff;
      border-radius: 8rpx;

      .Address1 {
        height: 104rpx;
        display: flex;
        padding-left: 30rpx;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #d2d2d2;

        .iconfont {
          width: 104rpx;
          height: 104rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 40rpx;
          color: #2093f5;
        }
      }

      .Address2 {
        height: 100rpx;
        display: flex;
        align-items: center;
        padding: 0 30rpx;
      }
    }
  }
</style>
